package Servlet;

/**
 * Created by 2015302580057 on 2017/7/12.
 */

import dao.UserDao;
import daoImpl.UserDaoImpl;
import entity.User;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String email = request.getParameter("myemail");
        String password = request.getParameter("password");
        // 处理注册请求之前，校验认证码是否有效
        String c_checkcode = request.getParameter("checkcode").trim();//获取用户输入的验证码
        String s_checkcode = (String) request.getSession().getAttribute("checkcode");//获取系统生成的验证码

        response.setContentType("text/json;charset=utf-8");

        UserDao dao = new UserDaoImpl();
        User u = dao.queryUserByEmail(email);
        PrintWriter pw = response.getWriter();
        JSONObject object = new JSONObject();//定义一个json对象，用来存储执行返回结果，0代表成功，1代表用户已存在，2代表添加失败
        if (u == null) {
            object.put("code", 1);//用户不存在
            pw.print(object);
        } else if (!(c_checkcode!=null && s_checkcode!=null && c_checkcode.equals(s_checkcode.trim()))){//检验验证码
            object.put("code", 2);//验证码不正确
            pw.print(object);
        } else if (!u.getPassword().equals(password)) {//检验密码
            object.put("code", 3);//密码错误
            pw.print(object);
        }else{
            object.put("code", 0);//认证成功
            pw.print(object);
            request.getSession().setAttribute("username",u.getUsername());
        }

        pw.close();


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);

    }
}
